<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>表单验证</title>
    <style>
        .error {
            color: red;
        }
    </style>
</head>
<body>
    <form id="loginForm" onsubmit="return validateForm()">
        <div>
            <label for="username">用户名:</label>
            <input type="text" id="username" name="username">
            <span id="usernameError" class="error"></span>
        </div>
        <div>
            <label for="password">密码:</label>
            <input type="password" id="password" name="password">
            <span id="passwordError" class="error"></span>
        </div>
        <button type="submit">提交</button>
    </form>

    <script>
        function validateForm() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const usernameError = document.getElementById('usernameError');
            const passwordError = document.getElementById('passwordError');

            usernameError.textContent = '';
            passwordError.textContent = '';

            if (username.trim() === '') {
                usernameError.textContent = '用户名不能为空';
                return false;
            }

            if (password.trim() === '' || password.length < 6) {
                passwordError.textContent = '密码不能为空且长度至少为6个字符';
                return false;
            }

            return true;
        }
    </script>
</body>
</html>
